<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.sn"
        placeholder="SN"
        style="width: 200px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.user_id"
        placeholder="用户ID"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-date-picker
        class="filter-item"
        v-model="listQuery.start"
        value-format="yyyy-MM-dd"
        type="date"
        @change="handleFilter"
        style="margin-left: 10px"
        placeholder="开始日期">
      </el-date-picker>
      -
      <el-date-picker
        class="filter-item"
        v-model="listQuery.end"
        type="date"
        @change="handleFilter"
        value-format="yyyy-MM-dd"
        placeholder="结束日期">
      </el-date-picker>
      <el-button
        v-waves
        type="primary"
        icon="el-icon-search"
        class="filter-item"
        style="margin-left: 10px;"
        @click="handleFilter"
      >搜 索</el-button>
      <el-button
        v-waves
        type="success"
        icon="el-icon-refresh"
        class="filter-item"
        style="margin-left: 10px;"
        @click="clearFilter"
      >清除筛选</el-button>
    </div>
    <div class="filter-container">
      <el-button
        v-waves
        type="success"
        icon="el-icon-download"
        class="filter-item"
        size="small"
        plain
        :loading="listLoading"
        @click="handleExport"
      >导出 Excel</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :border="false"
      fit
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column sortable="custom" prop="id" label="ID" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="sn" label="SN">
        <template slot-scope="{row}">
          <span>{{ row.sn }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="user_id" label="用户ID">
        <template slot-scope="{row}">
          <span>{{ row.user_id }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="amount" label="金额">
        <template slot-scope="{row}">
          <span>{{ +row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="pay_type" label="支付类型">
        <template slot-scope="{row}">
          <span>{{ row.pay_type_text }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" sortable="custom" prop="create_time" width="160">
        <template slot-scope="{row:{create_time}}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ create_time | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" sortable="custom" prop="update_time" width="160">
        <template slot-scope="{row}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ row.update_time | timeFilter }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      @pagination="refresh"
    />
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import api from '@/api'

const initQuery = {
  page: 1,
  pageSize: 10,
  total: 0,
  sort: '-id'
}

export default {
  name: 'Pay',
  components: {
    Pagination
  },
  directives: { waves },
  filters: {
    timeFilter(time) {
      return time ? parseTime(time, '{m}-{d} {h}:{i}') : ''
    }
  },
  data() {
    return {
      listLoading: false,
      list: [],
      listQuery: {},
      defaultSort: {},
      payTotal: 0
    }
  },
  created() {
    this.getPayTotal()
    this.parseQuery()
  },
  mounted() {
    this.getList()
  },
  methods: {
    getPayTotal() {
      api.finance.getPayTotal().then(response => {
        const { data } = response
        this.payTotal = data.total
      })
    },
    getList() {
      this.listLoading = true
      api.finance.payList({ ...this.listQuery }).then(response => {
        const { data } = response
        this.list = data.list
        this.listQuery.total = +data.totalCount
        this.listLoading = false
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 排序
     * @param data
     */
    sortChange(data) {
      const sortBy = (prop, order) => {
        if (prop && order === 'ascending') {
          this.listQuery.sort = `+${prop}`
        } else if (prop && order === 'descending') {
          this.listQuery.sort = `-${prop}`
        } else {
          this.listQuery.sort = ''
        }
      }
      const { prop, order } = data
      sortBy(prop, order)
      this.handleFilter()
    },
    /**
     * 刷新
     */
    refresh() {
      this.$router.push({
        path: '/finance/pay',
        query: this.listQuery
      })
    },
    /**
     * 过滤(筛选)
     */
    handleFilter() {
      // this.listQuery.page = 1
      this.refresh()
    },
    /**
     * 清除筛选
     */
    clearFilter() {
      this.listQuery = Object.assign({}, initQuery)
      this.defaultSort = {}
      this.refresh()
    },
    /**
     * 处理筛选条件
     */
    parseQuery() {
      const query = Object.assign({}, this.$route.query)
      let sort = '-id'
      this.listQuery = Object.assign({}, { ...initQuery, sort })
      if (Object.keys(query).length > 0) {
        // 注意这里的类型转换
        query.page && (query.page = +query.page)
        query.pageSize && (query.pageSize = +query.pageSize)
        query.total && (query.total = +query.total)
        query.status && (query.status = +query.status)
        query.sort && (sort = query.sort)
      }
      const sortSymbol = sort[0]
      const sortColumn = sort.slice(1, sort.length)
      this.defaultSort = {
        prop: sortColumn,
        order: sortSymbol === '+' ? 'ascending' : 'descending'
      }
      this.listQuery = { ...this.listQuery, ...query }
    },
    /**
     * 导出
     */
    async handleExport() {
      const formatJson = (filterVal, jsonData) => {
        return jsonData.map(v => filterVal.map(j => {
          return v[j]
        }))
      }
      this.listLoading = true
      const response = await api.finance.payList({ ...this.listQuery, export: true })
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', 'SN', '用户', '金额', '类型', '支付时间', '到帐时间']
        const filterVal = ['id', 'sn', 'user_id', 'amount', 'pay_type_text', 'create_time', 'update_time']
        const list = response.data
        const data = formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '进帐流水'
        })
      })
      this.listLoading = false
    },
    /**
     * 排序设置
     */
    handleSort(row) {
      api.category.changeSort({ ...row }).then(response => {
        this.$notify({
          title: '成功',
          message: response.message || '设置成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getList()
      }
    }
    next()
  }
}
</script>
